package com.android.duininsuoai.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.duininsuoai.R;
import com.android.duininsuoai.activity.mine.PaySuccessActivity;
import com.android.duininsuoai.app.BaseActivity;
import com.android.duininsuoai.fragment.member.Fragment_Mine_DirectBuy_Order;
import com.android.duininsuoai.model.detail.DirectBuyAliPayData;
import com.android.duininsuoai.model.detail.DirectBuyAliPayDataCallback;
import com.android.duininsuoai.model.detail.DirectBuyOrderPayMethodData;
import com.android.duininsuoai.model.detail.DirectBuyOrderPayMethodDataCallback;
import com.android.duininsuoai.model.detail.DirectBuyWXPayData;
import com.android.duininsuoai.model.detail.DirectBuyWXPayDataCallback;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.utils.alipay.PayResult;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 直购支付订单页
 */
public class DirectBuyPayOrderActivity extends BaseActivity {
    @BindView(R.id.firmorder_address_name)
    TextView addressName;
    @BindView(R.id.firmorder_address_phone)
    TextView addressPhone;
    @BindView(R.id.firmorder_address_address)
    TextView addressAddress;
    @BindView(R.id.firmorder_goods_img)
    ImageView goodsImg;
    @BindView(R.id.firmorder_goods_title)
    TextView goodsTitle;
    @BindView(R.id.firmorder_goods_money)
    TextView goodsPrice;
    @BindView(R.id.firmorder_goods_score)
    TextView goodsScore;
    @BindView(R.id.firmorder_bottom_money)
    TextView totalPrice;
    @BindView(R.id.firmorder_bottom_score)
    TextView totalScore;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.firmorder_bottom_buy)
    LinearLayout toBuy;
    @BindView(R.id.firmorder_goods_num)
    TextView goodsNum;
    @BindView(R.id.firmorder_goods_total_price)
    TextView subTotal;
    @BindView(R.id.firmorder_goodss_total_score)
    TextView subTotalScore;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.order_number_tv)
    TextView orderNumber;
    @BindView(R.id.pay_style_list)
    NestFullListView payStyleList;

    private boolean networkConnected;
    private DirectBuyPayOrderActivity mcontext;
    private String order_sn;
    private int pospay;
    private List<DirectBuyOrderPayMethodData.DataBean.PaymentBean> payment = new ArrayList<>();
    private String pay_id;
    private String pay_name;

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mcontext, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent mIntent = new Intent(Fragment_Mine_DirectBuy_Order.DIRECTBUY_ORDER_PAY);
                        mcontext.sendBroadcast(mIntent);
                        toPaySuccess();
                        finish();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ObjectUtils.toast(mcontext, "支付结果确认中");
                        }
                        else if (TextUtils.equals(resultStatus, "6001")) {
                            ObjectUtils.toast(mcontext, "支付取消");
//                            toPaySuccess();
//                            finish();
                        }
                        else if (TextUtils.equals(resultStatus, "6002")) {
                            ObjectUtils.toast(mcontext, "网络异常");
                        }
                        else if (TextUtils.equals(resultStatus, "5000")) {
                            ObjectUtils.toast(mcontext, "重复请求");
                        }
                        else {
                            // 其他值就可以判断为支付失败
                            ObjectUtils.toast(mcontext, "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void toPaySuccess() {
        Intent intent = new Intent(this, PaySuccessActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_directbuy_payorder);
        ButterKnife.bind(this);
        mcontext = DirectBuyPayOrderActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initTitle(0, "支付订单");
        initUI();
    }

    @OnClick({R.id.firmorder_bottom_buy
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.firmorder_bottom_buy:
                toPay();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initUI() {
        tv_right.setVisibility(View.INVISIBLE);
        order_sn = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ORDER_ID);
        orderNumber.setText(order_sn + "");
        getPayMethod();

        payStyleList.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                pospay = position;
                nestFullListView.updateUI();
                if (payment != null && payment.size() > 0) {
                    pay_id = payment.get(position).getPay_id();
                    pay_name = payment.get(position).getPay_name();
                }
            }
        });
    }

    //获取支付详情
    private void getPayMethod() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_PAYMETHOD;
        HashMap<String, String> map = new HashMap<>();
        map.put("order_sn", order_sn + "");

        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.post(address, header, map, dataCallback);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuyOrderPayMethodDataCallback dataCallback = new DirectBuyOrderPayMethodDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(DirectBuyOrderPayMethodData response, int id) {
            if (response.getCode() == 0 && response.getData() != null) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                DirectBuyOrderPayMethodData.DataBean data = response.getData();
                if (data.getAddress() != null && data.getAddress().getId() != null) {
                    DirectBuyOrderPayMethodData.DataBean.AddressBean addressData = data.getAddress();
                    addressName.setText(addressData.getName());
                    addressPhone.setText(addressData.getMobile());
                    addressAddress.setText(addressData.getArea() + addressData.getAddress());
                }
                goodsTitle.setText(data.getCart_goods().get(0).getGoods_name());
                //单价和积分
                goodsPrice.setText("¥" + data.getCart_goods().get(0).getGoods_price());
                goodsScore.setText(data.getCart_goods().get(0).getScore_price() + "积分");

                //总价和积分
                totalPrice.setText("¥" + data.getTotal().getGoods_amount());
                totalScore.setText(data.getTotal().getScore_amout() + "积分");

                //商品部分的总价和积分，运费
                subTotal.setText("¥" + data.getCart_goods().get(0).getSubtotal());
                subTotalScore.setText(data.getTotal().getScore_amout() + "");

                String goods_buy_num = data.getCart_goods().get(0).getQty();
                goodsNum.setText("x" + goods_buy_num);
                String goods_img_src = data.getCart_goods().get(0).getImg_src();
                ObjectUtils.photo(mcontext, goods_img_src, goodsImg);

                payment = data.getPayment();
                if (payment != null && payment.size() > 0) {
                    pay_id = payment.get(0).getPay_id();
                    pay_name = payment.get(0).getPay_name();
                }
                payStyleList.setAdapter(new NestFullListViewAdapter<DirectBuyOrderPayMethodData.DataBean.PaymentBean>(R.layout.item_pay, payment) {
                    @Override
                    public void onBind(int position, DirectBuyOrderPayMethodData.DataBean.PaymentBean testBean, NestFullViewHolder holder) {
                        holder.setText(R.id.pay_name, testBean.getPay_name());
                        ImageView view = (ImageView) holder.getView(R.id.pay_logo);
                        ObjectUtils.photo(mcontext, testBean.getThumb(), view);
                        if (pospay == position) {//最后选择的位置
                            holder.setChecked(R.id.item_list_mine_pay_check, true);
                        } else {
                            holder.setChecked(R.id.item_list_mine_pay_check, false);
                        }
                    }
                });
                payStyleList.updateUI();
            } else {
                if(response.getCode() == 40001){
                    ObjectUtils.reLogin(mcontext);
                }
                noData.setVisibility(View.VISIBLE);
                noDataTv.setText(response.getMsg());
                noDataTv.setVisibility(View.VISIBLE);
            }
        }
    };

    private void toPay() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY;
        HashMap<String, String> map = new HashMap<>();
        map.put("order_sn", order_sn + "");
        map.put("pay_id", pay_id + "");

        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            if (pay_name.equals("微信APP")) {
                HttpUtils.post(address, header, map, wxPayDataCallback);
            } else {
                HttpUtils.post(address, header, map, aliPayDataCallback);
            }
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    DirectBuyWXPayDataCallback wxPayDataCallback = new DirectBuyWXPayDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuyWXPayData response, int id) {
            if(response.getData()!=null&&response.getData().getPaycode()!=null&&response.getData().getPaycode().getAppid()!=null){
                //微信支付发起
                IWXAPI iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
                iwxapi.registerApp(ConstantsUrl.WX_APPID);
                PayReq req = new PayReq();
                req.appId = ConstantsUrl.WX_APPID;
                req.partnerId = response.getData().getPaycode().getPartnerid();
                req.prepayId = response.getData().getPaycode().getPrepayid();
                req.packageValue = response.getData().getPaycode().getWxpackage();
                req.nonceStr = response.getData().getPaycode().getNoncestr();
                req.timeStamp = response.getData().getPaycode().getTimestamp()+"";
                req.sign = response.getData().getPaycode().getSign();
                iwxapi.sendReq(req);
            }
        }
    };

    DirectBuyAliPayDataCallback aliPayDataCallback = new DirectBuyAliPayDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }

        @Override
        public void onResponse(DirectBuyAliPayData response, int id) {
            if (response.getData() != null && response.getData().getPaycode() != null) {
                final String orderInfo = response.getData().getPaycode();
                //支付宝支付发起
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(mcontext);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else {
                ObjectUtils.toast(mcontext, response.getMsg());
            }
        }
    };
}